package com.study.compose.beta.view

import android.util.Log
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import com.module.compose.base.composable.CommonItem
import com.module.compose.base.composable.swipToRefresh.ComposePullToRefresh
import com.study.compose.beta.R
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
 * 作者：zhangjunfei 2021/6/3 9:18 上午
 * 主页：https://gitee.com/ZhangQQ_123/projects
 * 描述：下拉刷新示例
 */
@Composable
fun SwipeToRefreshSample() {

    //刷新状态
    var refreshState by remember {
        mutableStateOf(false)
    }

    //加载更多状态
    var loadingMore by remember {
        mutableStateOf(true)
    }
    //item数量
    var itemCount by remember {
        mutableStateOf(20)
    }

    //rememberCoroutineScope 是一个可组合函数，会返回一个 CoroutineScope，该 CoroutineScope 绑定到调用它的组合点。调用退出组合后，作用域将取消。
    val scope = rememberCoroutineScope()

    ComposePullToRefresh(isRefreshing = refreshState, onRefresh = {
        refreshState = true
        //执行耗时操作
        scope.launch(Dispatchers.Main) {
            //在当前线程开启协程
            Log.e("协程", Thread.currentThread().name)
            //在io线程挂起两秒
            withContext(Dispatchers.IO) {
                delay(2000)
            }
            itemCount = 20
            //更新状态
            refreshState = false
        }

        Log.e("主线程", Thread.currentThread().name)
    }) {
        LazyColumn(Modifier.fillMaxWidth()) {
            items(itemCount) { index ->
                CommonItem(content = "下拉刷新$index", iconId = R.mipmap.icon_android)
            }

            item {
                if (loadingMore && itemCount < 100) {
                    scope.launch {
                        loadingMore = false
                        delay(2000)
                        loadingMore = true
                        itemCount += 10
                    }
                }
                Text(
                    text = if (itemCount < 100) "加载更多..." else "我是有底线的",
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(20.dp),
                    textAlign = TextAlign.Center
                )
            }
        }
    }
}
